define(function(require, exports, module) {
  var $ = require("$");
  var bootbox = require("bootbox");
  var dtUtil = require('datatableutil');
  require("bootstrap_commonrequire");
  var loader = require("./loader/loader");
  require("moment");
  require('daterangepicker.css');
  require('bootstrap-daterangepicker');
  require('select2.css');
  require('select2');

  exports.init = function(param) {

    $(document).ready(function() {
      // 蒙版
      loader.loading("数据加载中，请稍后……");
      // 加载自定义模板-条件区域
      var template = require("./dialstats.tpl");
      var Widget = require("widget");
      var Component = Widget.extend({
        template : template
      });
      new Component({
        renderTo : "queryAreaId"
      });
      
      // 判断省份是否为“总计”
      var province = "";
      // 判断应用名称是否为“总计”
      var apply = "";
      var countAll = "";
      // 显示类型
      var type = "province";
      

      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
        label : "日期"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });
      daterangeCom.setRangeToTodayWeek();
      
      
      // 绑定所有省份的名称下拉列表
      $.ajax({
        type : "POST",
        dataType : "json",
        url : "/poolnumber/queryAllAreas.do",
        async : false,
        success : function(data) {
          $("#areaid").select2({
            placeholder : "请选择省份名称",
            allowClear : true,
            data : data
          });
        },
        error : function(data) {
          bootbox.alertTimeout('初始化省份名称数据失败！');
        }
      });
      
      // 绑定应用下拉列表
      $.ajax({
        type : "POST",
        dataType : "json",
        url : "/condition/applyName.do",
        async : false,
        success : function(data) {
          $("#applyName").select2({
            placeholder : "请选择应用名称",
            allowClear : true,
            data : data
          });
        },
        error : function(data) {
          bootbox.alertTimeout('初始化应用名称数据失败！');
        }
      });
      
      // 绑定所有回呼号码下拉列表
      $.ajax({
        type : "POST",
        dataType : "json",
        url : "/callStatus/queryAllCallback.do",
        async : false,
        success : function(data) {
          $("#callbackNum").select2({
            placeholder : "请选择回呼号码",
            allowClear : true,
            data : data
          });
        },
        error : function(data) {
          bootbox.alertTimeout('初始化回呼号码数据失败！');
        }
      });
      
      
      // 设置查询条件
      function getCondition() {
        //获取查询条件
        var applyid = $('#applyName').val();
        var areaId = $('#areaid').val();
        var callbackNumber = $('#callbackNum').val();
        var queryStr = "";

        if (areaId != '' && areaId != null) {
          queryStr += ("p.area='" + areaId + "';");
        }
        
        if (applyid != '' && applyid != null) {
          queryStr += ("i.app_id=" + applyid + ";");
        }
        
        if (callbackNumber != '' && callbackNumber != null) {
          queryStr += ("i.chargeNumber=" + callbackNumber + ";");
        }
        
        // 获取时间查询参数
        var daterange = daterangeCom.getPickerRange();
        if (daterange) {
          var daterange = daterange.split("/");
          var startTime = daterange[0];
          var endTime = daterange[1];
          
          queryStr += ("i.create_time BETWEEN '" + startTime + " 00:00:00' AND '" + endTime + " 23:59:59'" + ";");
        }
        
        return queryStr;
      }
      
      //加载表单模板和数据
      var Table = require("table");
      // 按省份查询内容显示
      new Table({
        attrs : {
          id : "province_table",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.province_divId

      });
      
      // callState信息显示
      var datatable_province = $('#province_table').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : "/callStatus/queryDialStats.do",
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);

          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }

          if (type == "province") {
            // 添加自己的额外参数
            oSettings.jqXHR = $.ajax({
              "dataType" : 'json',
              "contentType" : "application/json;charset=UTF-8",
              "type" : "GET",
              "url" : sSource,
              "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
              "success" : function(json) {
                if (json.flag == '000000') {
                  // 隐藏蒙版
                  loader.noloading();
                  dtUtil.successCallback(json, aoData, fnCallback);
                } else {
                  oauth2Relogin();
                }
              }
            });
          }

        },
        "aoColumns" : [ {
          "sTitle" : "省份",
          "bSortable" : false,
          "mData" : "area",
          "mRender" : function(data, type, full) {
            countAll = data;
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + countAll +"</div>";
            else
              return countAll;
          }
        }, {
          "sTitle" : "呼叫次数",
          "bSortable" : true,
          "mData" : "call_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "接听次数",
          "bSortable" : true,
          "mData" : "rec_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "未接听次数",
          "bSortable" : true,
          "mData" : "unrec_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "接听成功率",
          "bSortable" : true,
          "mData" : "rec_rate",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        } ],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });
      
      
      // 按应用名称查询内容显示
      new Table({
        attrs : {
          id : "applytype_table",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.applytype_divId

      });
      
      // callState信息显示
      var datatable_application = $('#applytype_table').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : "/callStatus/queryDialStatsByApp.do",
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);

          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }

          if (type == "apply") {
            // 添加自己的额外参数
            oSettings.jqXHR = $.ajax({
              "dataType" : 'json',
              "contentType" : "application/json;charset=UTF-8",
              "type" : "GET",
              "url" : sSource,
              "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
              "success" : function(json) {
                if (json.flag == '000000') {
                  // 隐藏蒙版
                  loader.noloading();
                  dtUtil.successCallback(json, aoData, fnCallback);
                } else {
                  oauth2Relogin();
                }
              }
            });
          }

        },
        "aoColumns" : [ {
          "sTitle" : "应用名称",
          "bSortable" : false,
          "mData" : "appname",
          "sWidth" : "130%", 
          "mRender" : function(data, type, full) {
            countAll = data;
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + countAll +"</div>";
            else
              return countAll;
          }
        }, {
          "sTitle" : "呼叫次数",
          "bSortable" : true,
          "mData" : "call_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "接听次数",
          "bSortable" : true,
          "mData" : "rec_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "未接听次数",
          "bSortable" : true,
          "mData" : "unrec_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "接听成功率",
          "bSortable" : true,
          "mData" : "rec_rate",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        } ],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });
      
      
      // 按应用名称查询内容显示
      new Table({
        attrs : {
          id : "callback_table",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.callback_divId

      });
      
      // callState信息显示
      var datatable_callback = $('#callback_table').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : "/callStatus/queryDialStatsByCallBack.do",
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);

          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }

          if (type == "callback") {
            // 添加自己的额外参数
            oSettings.jqXHR = $.ajax({
              "dataType" : 'json',
              "contentType" : "application/json;charset=UTF-8",
              "type" : "GET",
              "url" : sSource,
              "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
              "success" : function(json) {
                if (json.flag == '000000') {
                  // 隐藏蒙版
                  loader.noloading();
                  dtUtil.successCallback(json, aoData, fnCallback);
                } else {
                  oauth2Relogin();
                }
              }
            });
          }

        },
        "aoColumns" : [ {
          "sTitle" : "回呼号码",
          "bSortable" : false,
          "mData" : "charge_number",
          "sWidth" : "130%", 
          "mRender" : function(data, type, full) {
            countAll = data;
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + countAll +"</div>";
            else
              return countAll;
          }
        }, {
          "sTitle" : "呼叫次数",
          "bSortable" : true,
          "mData" : "call_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "接听次数",
          "bSortable" : true,
          "mData" : "rec_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "未接听次数",
          "bSortable" : true,
          "mData" : "unrec_times",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "接听成功率",
          "bSortable" : true,
          "mData" : "rec_rate",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        } ],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });
      
      
      // 按主叫未接听原因查询内容显示
      new Table({
        attrs : {
          id : "reasons_table",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.reasons_divId

      });
      
      // callState信息显示
      var datatable_reasons = $('#reasons_table').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : "/callStatus/queryUnrecReasons.do",
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);

          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }

          if (type == "reasons") {
            // 添加自己的额外参数
            oSettings.jqXHR = $.ajax({
              "dataType" : 'json',
              "contentType" : "application/json;charset=UTF-8",
              "type" : "GET",
              "url" : sSource,
              "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
              "success" : function(json) {
                if (json.flag == '000000') {
                  // 隐藏蒙版
                  loader.noloading();
                  dtUtil.successCallback(json, aoData, fnCallback);
                } else {
                  oauth2Relogin();
                }
              }
            });
          }

        },
        "aoColumns" : [ {
          "sTitle" : "失败原因",
          "bSortable" : false,
          "mData" : "reason",
          "sWidth" : "120%", 
          "mRender" : function(data, type, full) {
            countAll = data;
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + countAll +"</div>";
            else
              return countAll;
          }
        }, {
          "sTitle" : "失败次数",
          "bSortable" : false,
          "mData" : "unrec_times",
          "sWidth" : "80%", 
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        }, {
          "sTitle" : "失败率",
          "bSortable" : false,
          "mData" : "rec_rate",
          "sWidth" : "80%",
          "mRender" : function(data, type, full) {
            if (countAll == '总计')
              return "<div class='fontcir' style='font-size:115%;font-weight:bold;'>" + data +"</div>";
            else
              return data;
          }
        } ],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });
      
      
      
      // 维度分析，省市
      $('#btnByProvince').click(function() {
//        datatable_province.fnDraw();
        loader.loading("数据加载中，请稍后……");
        type = 'province';
        // 显示下拉框
        $('#province').show();
        $('#applytype').hide();
        $('#callback').hide();
        // 清空下拉框原有数据
        $("#applyName").select2("val", "");
        $("#callbackNum").select2("val", "");
        // 显示表单
        $('#applytype_div').hide();
        $("#province_div").show();
        $("#callback_div").hide();
        $("#reasons_div").hide();
        //蒙版
        datatable_province.fnDraw();
      });
      
      // 维度分析，应用名称
      $('#btnByApplication').click(function() {
//        datatable_application.fnDraw();
        loader.loading("数据加载中，请稍后……");
        type = 'apply';
        // 显示下拉框
        $('#province').hide();
        $('#applytype').show();
        $('#callback').hide();
        // 清空下拉框原有数据
        $("#areaid").select2("val", "");
        $("#callbackNum").select2("val", "");
        // 显示表单
        $('#applytype_div').show();
        $("#province_div").hide();
        $("#callback_div").hide();
        $("#reasons_div").hide();
        //蒙版
        datatable_application.fnDraw();
      });
      
      // 维度分析，回呼号码
      $('#btnByCallback').click(function() {
        loader.loading("数据加载中，请稍后……");
        type = 'callback';
        // 显示下拉框
        $('#province').hide();
        $('#applytype').hide();
        $('#callback').show();
        // 清空下拉框原有数据
        $("#applyName").select2("val", "");
        $("#areaid").select2("val", "");
        // 显示表单
        $('#callback_div').show();
        $("#province_div").hide();
        $("#applytype_div").hide();
        $("#reasons_div").hide();
        //蒙版
        datatable_callback.fnDraw();
      });
      
      // 维度分析，主叫未接听原因统计
      $('#btnByReasons').click(function() {
        loader.loading("数据加载中，请稍后……");
        type = 'reasons';
        // 显示下拉框
        $('#province').hide();
        $('#applytype').hide();
        $('#callback').hide();
        // 清空下拉框原有数据
        $("#applyName").select2("val", "");
        $("#areaid").select2("val", "");
        $("#callbackNum").select2("val", "");
        // 显示表单
        $("#reasons_div").show();
        $('#callback_div').hide();
        $("#province_div").hide();
        $("#applytype_div").hide();
        //蒙版
        datatable_reasons.fnDraw();
      });


      
      //查询按钮
      $('#querybtn').click(function() {
        //蒙版
        loader.loading("数据加载中，请稍后……");
        datatable_province.fnFilter("");
        datatable_application.fnFilter("");
        datatable_callback.fnFilter("");
        datatable_reasons.fnFilter("");
        return false;
      });

      //重置按钮
      $('#restbtn').click(function() {
        //蒙版
        loader.loading("数据加载中，请稍后……");
        $("#applyName").select2("val", "");
        $("#areaid").select2("val", "");
        $("#callbackNum").select2("val", "");
        daterangeCom.setRangeToToday();
        
        datatable_province.fnFilter("");
        datatable_application.fnFilter("");
        datatable_callback.fnFilter("");
        datatable_reasons.fnFilter("");
        return false;
      });

    });

  };
});
